const momentService = require('../service/moment.service')
const petService = require('../service/petlist.service')

class PetController {
    async create(ctx, next) {
        console.log('petctx', ctx)
        // 获取数据

        const { user_id, name, age, gender, breed, photo, vaccine, weight, description }  = ctx.request.body
        try {
            let photoBuffer = Buffer.from(photo,'base64')
            console.log('per',photoBuffer)
            const result = await petService.create(user_id, name, age, gender, breed, photoBuffer, vaccine, weight, description)

            ctx.body = result
        } catch (error) {
            console.log('插入宠物失败' ,error)
        }

    }

    async list(ctx, next) {

    }

    async detail(ctx, next) {
        const { petId } = ctx.params
        console.log('petId', petId)
        const result = await petService.getPetDetail(petId)
        const imageBlob = result[0].photo
        const imageBuffer = Buffer.from(imageBlob)
        const imageBase64 = imageBuffer.toString('base64')
        result[0].photo = imageBase64
        ctx.body = result
    }

    async remove(ctx, next) {

    }

    async update(ctx, next) {
        
    }

    async kindsdetail (ctx, next) {
        console.log('first')
        try {
            const result = await petService.getPetKinds()

            ctx.body = result
        } catch (error) {
            console.log(error)
        }
    }

    async petbreeddetail(ctx, next) {
        console.log('first')
        try {
            const result = await petService.getBreedsDetail()
            console.log('result2',result)
            result.forEach(item => {
                item.petBreedList.forEach(item2=> {
                 if(!item2.id) return

                    // let imageUrl = item.petBreedList.image_url
                    console.log('item11',item2)
                    const imageBlob = item2.image_url
                    const imageBuffer = Buffer.from(imageBlob)
                    const imageBase64 = imageBuffer.toString('base64')
                    console.log('imageBase64',imageBase64)
                    item2.image_url = imageBase64
                })
                
            });
            console.log('result',result)
            // const imageBlob = result[0].avatar
            // const imageBuffer = Buffer.from(imageBlob)
            // const imageBase64 = imageBuffer.toString('base64')
            // result[0].avatar = imageBase64
            ctx.body = result
        } catch (error) {
            console.log(error)
        }
    }

    async getPetList(ctx, next) {
        const { userId } = ctx.params
        const result = await petService.getPetList(userId)
        console.log('res',result)
        ctx.body = result
    }
}

module.exports = new PetController()
